
package com.lt.test.provider.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.lt.test.api.KtPurchaseOrderService;
import com.lt.test.api.KtTakeStockService;
import com.lt.test.common.util.DateUtil;
import com.lt.test.common.util.StringUtils;
import com.lt.test.provider.dao.KtShopLossprofitDao;
import com.lt.test.provider.dao.KtShopLossprofitItemDao;
import com.lt.test.provider.dao.KtTakeStockDao;
import com.lt.test.provider.dao.KtTakeStockItemDao;
import com.lt.test.entity.DTO.PageDTO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

import static com.lt.test.common.util.DateUtil.formatDate;


@Service(version = "1.0.0")
public class KtTakeStockServiceImpl implements KtTakeStockService {

	@Resource
	private KtTakeStockDao ktTakeStockDao;
	
	@Resource
	private KtTakeStockItemDao ktTakeStockItemDao;
	
	@Resource
	private KtShopLossprofitDao ktShopLossprofitDao;
	
	@Resource
	private KtShopLossprofitItemDao ktShopLossprofitItemDao;
	
	@Resource
	private KtPurchaseOrderService ktPurchaseOrderService;

	public List query(Map parameter) {
		return ktTakeStockDao.query(parameter);
	}
	

	public int create(Map parameter) {
		return ktTakeStockDao.create(parameter);
	} 
	
	public int update(Map parameter) {
		return ktTakeStockDao.update(parameter);
	}
	
	public int save(Map parameter) {
		return ktTakeStockDao.save(parameter);
	}
	 
	public int delete(Long id) {
		return ktTakeStockDao.delete(id);
	}
    public Map findById(Long id) {
		return ktTakeStockDao.findById(id);
	} 
	public int batch(List values){
    	return ktTakeStockDao.batch(values);
    }
	public int batchUpdate(List values) {
		return ktTakeStockDao.batchUpdate(values);
	}
	public int batchDelete(List values) {
		return ktTakeStockDao.batchDelete(values);
	}

	@Override
	public Map<String,Object> verifyTakeStock(Map parameter){
		String beginTime = formatDate(new Date(), "yyyy-MM-dd");
		parameter.put("beginTime",beginTime);
		List<Map<String, Object>> list = queryTakeStock(parameter);
		if (list.size() > 0){
			return list.get(0);
		}
		return null;
	}

	@Override
	public String saveTakeStock(Map parameter) {
		String takeId = parameter.get("takeId") == null ? "" : parameter.get("takeId").toString();
		String shopId = parameter.get("shopId").toString();
		String userId = parameter.get("userId").toString();
		if(StringUtils.isNullOrEmpty(takeId)) {
			Map userMap = getUserInfo(userId);
			String time = formatDate(new Date(), "yyyyMMddHHmmss");
			String id = "TAKE" + time + "" + shopId;
			parameter.put("id", id);
			parameter.put("status", '1');
			parameter.put("userName", userMap.get("userName").toString());
			parameter.put("operateTime", new Date());
			ktTakeStockDao.create(parameter);
			return id;
		}else {
			parameter.put("id", takeId);
			parameter.put("operateTime", new Date());
			ktTakeStockDao.update(parameter);
			return takeId;
		}
	}

	@Override
	public int updateTakeStock(Map parameter) {
		String takeId = parameter.get("takeId").toString();
		parameter.put("id", takeId);
		parameter.put("status", '0');

		return update(parameter);
	}

	@Override
	public List<Map<String, Object>> queryTakeStock(Map parameter) {
		String shopId = parameter.get("shopId").toString();
  		String takeId = parameter.get("takeId") == null ? "" : parameter.get("takeId").toString();
		String beginTime = parameter.get("beginTime") == null ? "" : parameter.get("beginTime").toString();
		String endTime = parameter.get("endTime") == null ? "" : parameter.get("endTime").toString();
		String type = parameter.get("type") == null ? "" : parameter.get("type").toString();
		return ktTakeStockDao.queryKtTakeStockList(shopId,takeId,type,beginTime, endTime);
	}

	public Map getUserInfo(String userId){
		Map userMap = ktTakeStockDao.getUserInfo(userId);
		String userName = userMap.get("userName") == null ? userMap.get("mobile").toString() : userMap.get("userName").toString();
		userMap.put("userName", userName);
		return userMap;
	}


	@Override
	public List<Map<String, Object>> getKtTakeAnalysis(Map parameter) {
		// TODO Auto-generated method stub
		String shopId = parameter.get("shopId") == null ? null : parameter.get("shopId").toString();
		String date = parameter.get("date") == null ? null : parameter.get("date").toString();
		return ktTakeStockDao.getKtTakeAnalysis(shopId,date);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveKtShopLossProfit(Map parameter) {
		// TODO Auto-generated method stub
		String id = parameter.get("id") == null ? null : parameter.get("id").toString();
		String userId = parameter.get("operator").toString();
		Date now = new Date();
		if(StringUtils.isNullOrEmpty(id)){
			id = StringUtils.getUUID();
			parameter.put("state", "0");
			parameter.put("id", id);
			parameter.put("createUser", userId);
			parameter.put("createTime", now);
			ktShopLossprofitDao.create(parameter);
			String prodList = parameter.get("prodList").toString();
			JSONArray dataArray = JSONArray.fromObject(prodList);
			List<Map> orderItemList = new ArrayList<Map>();
			List<Map> takeItemList = new ArrayList<Map>();
			for (int i = 0; dataArray.size() > 0 && i < dataArray.size(); i++) {
				JSONObject obj = dataArray.getJSONObject(i);
				Map orderItem = (Map) obj.toBean(obj, Map.class);
				Map takeItem = new HashMap();
				orderItem.put("id", StringUtils.getUUID());
				orderItem.put("orderId", id);
				orderItem.put("createTime", now);
				orderItem.put("createUser", userId);
				orderItem.put("state", "0");
				orderItemList.add(orderItem);
				takeItem.put("id", obj.get("takeItemId"));
				takeItem.put("approveFlag", "1");
				takeItemList.add(takeItem);
			}
			if(orderItemList.size() > 0){
				ktShopLossprofitItemDao.batch(orderItemList);
			}
			if(takeItemList.size() > 0 ){
				ktTakeStockItemDao.batchUpdate(takeItemList);
			}
			
			
			//修改take_item 状态
			
		}else{
			parameter.put("modifyUser", userId);
			parameter.put("modifyTime", now);
			ktShopLossprofitDao.update(parameter);
			ktShopLossprofitItemDao.deleteItems(id);
			String prodList = parameter.get("prodList").toString();
			JSONArray dataArray = JSONArray.fromObject(prodList);
			List<Map> orderItemList = new ArrayList<Map>();
			for (int i = 0; dataArray.size() > 0 && i < dataArray.size(); i++) {
				JSONObject obj = dataArray.getJSONObject(i);
				Map orderItem = (Map) obj.toBean(obj, Map.class);
				orderItem.put("id", StringUtils.getUUID());
				orderItem.put("orderId", id);
				orderItem.put("createTime", now);
				orderItem.put("createUser", userId);
				orderItem.put("state", "0");
				orderItemList.add(orderItem);
			}
			ktShopLossprofitItemDao.batch(orderItemList);
		}
	}


	@Override
	public PageDTO<Map<String, Object>> getShopLossProfitListByPage(Map parameter) {
		// TODO Auto-generated method stub
		Integer page = Integer.valueOf(parameter.get("page").toString());
		Integer pageSize = Integer.valueOf(parameter.get("rows").toString());
		String filters = parameter.get("filters") == null ? null : parameter.get("filters").toString();
		Long beginNum = (long) ((page - 1) * pageSize + 1);
		Long endNum = beginNum + pageSize - 1;
		List<Map<String,Object>> infoList = null;
		int recordCount = 0;

		String shopId = null;
		String beginTime = null;
		String endTime = null;
		if(filters != null && !filters.trim().equals("")) {
			JSONObject jsonObject = JSONObject.fromObject(filters);
			JSONArray jsonArray = (JSONArray) jsonObject.get("rules");
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject result = (JSONObject) jsonArray.get(i);
				if ("shopId".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))) {
					shopId = result.getString("data");
				}
				if ("beginTime".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))) {
					beginTime = result.getString("data");
				}
			}
		}

		infoList = ktShopLossprofitDao.getKtShopLossprofitListByPage(beginNum, endNum, shopId, beginTime);
		recordCount = Integer.valueOf(ktShopLossprofitDao.getKtShopLossprofitListSize(shopId, beginTime).get("total").toString());
		PageDTO<Map<String,Object>> result = new PageDTO<>(page, pageSize, infoList, recordCount);
		return result;
	}


	@Override
	public List<Map<String, Object>> getShopLossProfitItems(Map parameter) {
		// TODO Auto-generated method stub
		String id = parameter.get("id").toString();
		return ktShopLossprofitItemDao.getItemsByOrderId(id);
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void confirmShopLossProfit(Map parameter) {
		// TODO Auto-generated method stub
//		Map instockMap = new HashMap();
//		instockMap.put("shopId", "1");
//		instockMap.put("amt", "1");
//		instockMap.put("type", "7");
//		JSONArray array = new JSONArray();
//		JSONObject obj = new JSONObject();
//		obj.put("productCode", "1");
//		obj.put("quantity", "1");
//		obj.put("shopId", "1");
//		obj.put("price", "1");
//		obj.put("amt", "1");
//		array.add(obj);
//		instockMap.put("prodList", array.toString());
//		ktPurchaseOrderService.saveShopInstockOrder(instockMap);
		
		
		String batchNo = parameter.get("orderId").toString();
		String shopId = parameter.get("shopId").toString();
		String prodList = parameter.get("prodList").toString();
		String userId = parameter.get("operator").toString();
		Date now = new Date();
		String nowStr = DateUtil.formatDate(now, "yyyy-MM-dd HH:mm:ss");
		Map instockMap = new HashMap();
		instockMap.put("shopId", shopId);
		instockMap.put("type", "7");
		instockMap.put("batchNo", batchNo);
		instockMap.put("prodList", prodList);
		
		JSONArray dataArray = JSONArray.fromObject(prodList);
		if(dataArray.size() > 0){
			//数据不为空 保存入库单
			ktPurchaseOrderService.saveShopInstockOrder(instockMap);
			List<LinkedHashMap<String,Object>> itemList = new ArrayList<LinkedHashMap<String,Object>>();
			//修改损益单明细状态
			for (int i = 0; i < dataArray.size(); i++) {
				JSONObject obj = dataArray.getJSONObject(i);
				LinkedHashMap<String,Object> item = new LinkedHashMap<String,Object>();
				item.put("state", "1");
				item.put("modifyTime", nowStr);
				item.put("modifyUser", userId);
				item.put("orderId", batchNo);
				item.put("productCode", obj.getString("productCode"));
				itemList.add(item);
			}
			ktShopLossprofitItemDao.batchUpdateItems(itemList);
			
			List<Map<String,Object>> unFinishItems = ktShopLossprofitItemDao.getUnFinishItems(batchNo, "0");
			if(unFinishItems.size() > 0){
				Map orderMap = new HashMap();
				orderMap.put("state", "1");
				orderMap.put("id", batchNo);
				orderMap.put("modifyUser", userId);
				orderMap.put("modifyTime", now);
				ktShopLossprofitDao.update(orderMap);
			}
		}
	}


	@Override
	public void saveKtProdMove(List<Map<String,String>> parameter) {
		ktTakeStockDao.updateProdMove(parameter);
	}


	@Override
	public void saveMonthSettlement(Map parameter) {
		Date date = new Date();
		parameter.put("id", date.getTime());
		ktTakeStockDao.updateMonthSettlement(parameter);
	}


	@Override
	public List<Map<String, Object>> queryMonthSettlement(Map parameter) {
		// TODO Auto-generated method stub
		return ktTakeStockDao.getMonthSettlementList(parameter);
	}


	@Override
	public int delMonthSettlement(Map parameter) {
		return ktTakeStockDao.delMonthSettlement(parameter);
	}


}
